/**
 * 需求：
 *    1. 当页面默认没有操作滚动条时，底部添加一条数据，让滚动条置底
 *    2. 当页面默认有操作滚动条时，底部添加一条数据，让滚动条保持原样
 */

import React from "react";
import "./App.css";

class App extends React.Component {
  state = {
    list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10],
  };

  add() {
    this.setState((state) => ({
      list: [...state.list, state.list.length + 1],
    }));
  }

  handleWheel = () => {
    console.log("handleWheel");
    this.isWheel = true;
  };

  getSnapshotBeforeUpdate(prevProps: Readonly<{}>, prevState: Readonly<{}>) {
    // 有操作滚轮，则返回当前滚动条位置，否则返回 null
    if (this.isWheel) {
      return document.querySelector(".container")?.scrollTop;
    }
    return null;
  }

  /**
   * 更新完成触发
   */
  componentDidUpdate(prevProps, prevState, snapshot) {
    console.log("snapshot", snapshot);
    const containerEl = document.querySelector(".container");
    containerEl.scrollTop = snapshot ? snapshot : containerEl?.scrollHeight;
  }

  render() {
    const { list } = this.state;

    return (
      <div>
        <h1>App</h1>

        <button onClick={() => this.add()}>底部添加</button>

        <div className="container" onWheel={this.handleWheel}>
          {list.map((item) => (
            <div key={item} className="item">
              #{item}
            </div>
          ))}
        </div>
      </div>
    );
  }
}

export default App;
